<!--
 * @Descripttion: 组织机构管理
 * @version:
 * @Author: 穆宏宇
 * @Date: 2020-09-21 14:23:40
 * @LastEditors: 穆宏宇
 * @LastEditTime: 2020-11-18 18:43:30
-->
<template>
	<div class="organization">
		<el-dialog title="是否需要审批" :visible.sync="dialogTypeVisible" width="30%" :before-close="handleRoleClose"
			:close-on-click-modal="false" :close-on-press-escape="false">
			<div class="selectRole">
				<el-select v-model="sfxysp" placeholder="请选择是否需要审批">
					<el-option label="是" value="1"></el-option>
					<el-option label="否" value="0"></el-option>
				</el-select>
			</div>
			<span slot="footer" class="dialog-footer">
				<el-button @click="dialogTypeVisible = false">取 消</el-button>
				<el-button type="primary" @click="confirmType">确 定</el-button>
			</span>
		</el-dialog>
		<el-row :gutter="10">
			<el-col :span="6">
				<el-card class="box-card" :body-style="{ overflowY: 'auto', height: '74.5vh' }">
					<div slot="header" class="clearfix">
						<i class="el-icon-menu orgIcon"></i>
						<span>组织机构</span> 
						<el-input style="margin-top: 10px;" size="small" v-model="filterText" placeholder="请先展开组织再搜索" clearable></el-input>
					</div>
					<el-tree  
						ref="space" 
						:data="treeData" 
						node-key="id" 
						:check-on-click-node="true" 
						:props="defaultProps" 
						:filter-node-method="filterNode"
						@node-click="changeTree"     
						:load="loadNode"
				 		lazy
					>
						<span class="custom-tree-node" slot-scope="{ node }"> 
							<span>{{ node.label }}</span>
						</span>
					</el-tree>
				</el-card>
			</el-col>
			<el-col :span="18">
				<el-card class="box-card">
					<div slot="header" class="clearfix">
						<i class="el-icon-menu orgIcon"></i>
						<span>机构管理</span>
						<!-- <el-button style="float: right" type="primary" size="mini" @click="handleOpen('add')"
              >新增</el-button
            > -->

						<el-tooltip content="删除" placement="top" style="margin-left: 20px;">
							<el-button icon="el-icon-delete" size="mini" @click="deleteOrgFn(form)">
							</el-button>
						</el-tooltip>
						<el-tooltip content="添加" placement="top">
							<el-button icon="el-icon-plus" size="mini" @click="handleOpen('add', form)">
							</el-button>
						</el-tooltip>
						<el-tooltip content="绘制审批" placement="top">
							<el-button icon="el-icon-warning-outline" size="mini" @click="goActiviti(form)">
							</el-button>
						</el-tooltip>
						<el-tooltip content="修改是否需要审批" placement="top">
							<el-button icon="el-icon-document" size="mini" @click="editSp(form)">
							</el-button>
						</el-tooltip>
					</div>
					<el-form :label-position="'right'" :rules="rules" label-width="120px" :model="form" label-suffix=":"
						ref="form" style="margin-top: 20px;">
						<el-row>
							<el-col :span="12" v-if="parentName.length>0">
								<el-form-item label="上级机构">
									{{ parentName }}
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="机构名称" prop="name">
									<el-input v-model="form.name"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="类型" prop="type">
									<el-select v-model="form.type" placeholder="请选择类型" clearable
										@change="changeType($event)">
										<el-option value="1" label="组织"></el-option>
										<el-option value="2" label="部门"></el-option>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="组织类型">
									<el-select v-model="form.organizationType" placeholder="请选择类型"
										:disabled="form.type == 2" clearable>
										<el-option value="1" label="供货组织"></el-option>
										<el-option value="2" label="采购组织"></el-option>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="电话号码" prop="tel">
									<el-input v-model="form.tel"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="单位地址">
									<el-input v-model="form.addr"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="组织机构编码">
									<el-input v-model="form.organizationCode"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="排序">
									<el-input-number v-model="form.sortValue"
										onKeypress="return (/[\d]/.test(String.fromCharCode(event.keyCode)))"
										:controls="false" :max="999999"></el-input-number>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="描述">
									<el-input v-model="form.describe"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="是否需要审批">
									<el-radio-group v-model="form.sfxysp">
										<el-radio label="1">是</el-radio>
										<el-radio label="0">否</el-radio>
									</el-radio-group>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="结算方式">
									<el-radio-group v-model="form.settlementMethod">
										<el-radio label="1">未税结算</el-radio>
										<el-radio label="2">含税结算</el-radio>
									</el-radio-group>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="组织id">
									<el-input v-model="form.id" disabled></el-input>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-button type="primary" @click="handleSubmit" style="float: right;">保 存</el-button>
						</el-row>

						<!-- todo 显示供应商信息 -->
					</el-form>
				</el-card>
			</el-col>
		</el-row>
	</div>
</template>

<script>
	// import treeJson from './tree.json'

	import columns from './columns'
	import {
		getOrgTreeLazy,
		createOrg,
		deleteOrg,
		getOrgTree,
		getAllOrgList,
		editSpByOrgId,selectSpByOrgId,
		insertOrg,updateOrg,deleteTOrgById,
		getOrgLazyTree
	} from '@/api/admin.api'

	import {
		checkPhone
	} from '@/validations/validate'
	import {
		createUuid
	} from '@/util/common'
	
	import {
		getOrgTreeApi
	} from '@/api/itemPoolApi.js'
	export default {
		name: 'organization',
		data() {
			return {
				uuid: '',
				columns,
				// 左侧树
				treeData: [],
				// 右侧树
				treeDataTable: [],
				defaultProps: {
					children: 'children',
					label: 'name',
					isLeaf: 'leaf'
				},
				// 分页数据
				pageData: {
					// 当前分页
					pageNum: 1,
					// 分页条数
					pageSize: 10,
					// 数据总数
					total: 0,
				},
				// 表格选中数据
				tableSelectData: [],
				// 显示弹窗
				dialogVisible: false,
				editRow:{},
				// 弹窗类型 add 新增 ；edit 查看|编辑
				type: 'add',
				// 弹窗标题
				dialogTitle: '',
				// 弹窗中表单数据
				form: {},
				// 上级父级
				parentName: '',
				dialogTypeVisible:false,
				sfxysp:0,
				rules: {
					name: [{
						required: true,
						trigger: 'blur',
						message: '机构名称不能为空'
					}],
					tel: [{
							required: true,
							trigger: 'blur',
							message: '电话号码不能为空'
						},
						{
							validator: checkPhone,
							trigger: 'blur'
						},
					],
					type: [{
						required: true,
						trigger: 'change',
						message: '机构类型不能为空'
					}],
					// organizationType: [{
					// 	required: true,
					// 	trigger: 'change',
					// 	message: '组织类型不能为空'
					// }]
				},
				filterText: ''
			}
		},
		watch: {
			filterText(val) {
				this.$refs.space.filter(val)
			}
		},
		created() {
			this.getOrgTreeEvent()
		},
		methods: {
			
			changeType(e) {
				console.log("------" + e);
				if (e == 2) {
					this.form.organizationType = '';
				}
			},
			goActiviti(row) {
				if (row.id == undefined) {
					// this.$message({
					// 	message: '请选择组织或部门',
					// 	type: 'error',
					// })
					// return;
					row.id = row.parentId;
				}
				localStorage.setItem("type", 0);
				this.$router.push({
					path: "/activiti?type=0&deptId=" + row.id
				})
			},
			// 获取组织树
			getOrgTreeEvent() {
				var that = this;
				getOrgLazyTree({
					id:0
				}).then(res => {
					that.treeData = res
					this.$nextTick(() => {
						this.$set(this.editFormOptions[0].props, 'options', that.treeData)
					})
					console.log(that.treeData)
				})
				that.form = {};
			},
			// 组织机构节点数据
			loadNode(node, resolve) {
				getOrgLazyTree({
					id:node.data.id
				}).then((res) => {
					if (node.data.type < 4) {
						return resolve(res)
					} else { 
						return resolve([])  
					}
				})
			},
			editSp(row){
				// 修改用户身份
				var that = this;
				if(row.id){
					selectSpByOrgId({
						id:row.id
					}).then(res=>{
						var sfxysp = res.sfxysp
						if(sfxysp){
							that.sfxysp = sfxysp;
						}
					})
					this.editRow = row;
					this.dialogTypeVisible = true;
				}else{
					this.$message.error("请选择组织");
				}
			},
			// 确定已选身份
			confirmType() {
				console.log(123);
				editSpByOrgId({
					sfxysp: this.sfxysp,
					id: this.editRow.id
				}).then((res) => {
					if(res == 1){
						this.$message.success("修改成功")
						this.dialogTypeVisible = false
						this.getOrgTreeEvent()
					}else{
						this.$message.error("修改失败")
					}
				})
			},
			// 打开弹窗 查详情
			handleOpen(type, row) {
				var that = this;
				// if(row.id == undefined){
				// 	this.$message({
				// 		message: '请选择组织或部门',
				// 		type: 'error',
				// 	})
				// 	return;
				// }
				this.uuid = createUuid()
				this.type = type
				if (type === 'add') {
					if (row.id == undefined) {
						return;
					}
					const {
						name,
						id
					} = row
					this.form = {
						parentId: id
					}
					this.parentName = name
				} else {
					this.parentName = ''
					const {
						name,
						tel,
						addr,
						organizationCode,
						sortValue,
						describe,
						parentId,
						id,
						sfxysp,
						settlementMethod
					} = row
					this.form = {
						name,
						tel,
						addr,
						organizationCode,
						sortValue,
						describe,
						id,
						parentId,
						sfxysp,
						settlementMethod
					}
				}

				// this.dialogVisible = true
			},
			// 确定
			handleSubmit() {
				var data = this.form;
				console.log(this.form);
				this.$refs.form.validate((valid) => {
					if (valid) {
						if (this.form.type == 1) {
							if (this.form.organizationType == '' || this.form.organizationType == null) {
								this.$message({
									message: '请选择组织类型',
									type: 'error',
								})
								return;
							}
						}
						if(this.form.id){
							this.form.updateTime = null;
							this.form.createTime = null;
							updateOrg(this.form, this.uuid).then((res) => {
								var type = 'success';
								var msg = this.type == 'add' ? '添加成功！' : '保存成功'
								if (res == '有流程定义需要删除！' || res == '有未处理的审批流程！') {
									msg = res;
									type = 'error'
								}
							
								this.$alert(msg, '提示', {
									confirmButtonText: '确定',
									type: type,
									callback: (action) => {
										this.dialogVisible = false
										// this.getOrgTreeEvent()
										if (res != '有流程定义需要删除！' || res != '有未处理的审批流程！') {
											// location.reload();
											this.getOrgTreeEvent()
										}
									},
								})
							})
						}else{
							this.form.code = this.orgCode
							insertOrg(this.form, this.uuid).then((res) => {
								var type = 'success';
								var msg = this.type == 'add' ? '添加成功！' : '保存成功'
								if (res == '有流程定义需要删除！' || res == '有未处理的审批流程！') {
									msg = res;
									type = 'error'
								}
							
								this.$alert(msg, '提示', {
									confirmButtonText: '确定',
									type: type,
									callback: (action) => {
										this.dialogVisible = false
										// this.getOrgTreeEvent()
										if (res != '有流程定义需要删除！' || res != '有未处理的审批流程！') {
											// location.reload();
											this.getOrgTreeEvent()
										}
									},
								})
							})
						}
					}
				})
			},
			// 删除组织
			deleteOrgFn(row) {
				if (row.id == undefined) {
					// this.$message({
					// 	message: '请选择组织或部门',
					// 	type: 'error',
					// })
					// return;
					row.id = row.parentId;
				}
				this.$confirm('确定删除此组织吗?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
				}).then(() => {
					 deleteTOrgById(row).then((res) => {
						this.$message({
							message: '删除成功',
							type: 'success',
						})
						this.getOrgTreeEvent()
					})
				})
			},
			// 关闭弹窗
			handleClose(data) {
				console.log(data)
			},
			//表格最大高度
			tableMaxHeight() {
				return window.innerHeight - 160
			},
			// 左侧树点击
			changeTree(item) {
				debugger
				this.orgId = item.id
				this.orgCode = item.code
				this.treeDataTable = [item]
				this.form = item;
				this.type = 'edit';
				this.parentName = '';
			},
			//优化之后的代码 不管有几级都可以适用,不过用了递归
			filterNode(value, data, node) {
				console.log(value, data, node)
				if (!value) {
					return true
				}
				let _array = [] //这里使用数组存储 只是为了存储值。
				this.getReturnNode(node, _array, value)
				let result = false
				_array.forEach(item => {
					result = result || item
				})
				return result
			},
			getReturnNode(node, _array, value) {
				let isPass = node && node.label && node.label.indexOf(value) !== -1
				isPass ? _array.push(isPass) : ''
				if (!isPass && node.level != 1 && node.parent) {
					this.getReturnNode(node.parent, _array, value)
				}
			}
		}
	}
</script>

<style scoped lang='scss'>
	.organization {
		.box-card {
			height: calc(100vh - 120px);
		}

		.orgIcon {
			padding-right: 6px;
			color: $--color-primary;
		}

		.e-search-box .e-search-form {
			padding-right: 0;
		}
	}
</style>

<style lang="scss" scoped>
	.is-current {
		&>.el-tree-node__content {
			color: #fff;
			background: $--color-primary !important;
		}
	}

	.el-tree-node__children {
		background: #fff !important;
	}

	.el-tree-node__content:hover {
		background: rgba(0, 0, 0, 0.1);
	}

	.organization {
		.el-input-number {
			width: 100%;

			.el-input__inner {
				text-align: left;
			}
		}

		.box-card-tree {
			.el-card__body {
				height: calc(100% - 100px);
			}
		}

		th,
		td,
		tr {
			text-align: left !important;
		}
	}

	::v-deep .el-tree>.el-tree-node {
		min-width: 100%;
		display: inline-block;
		overflow: auto;
	}
</style>
<style lang="css">
	.el-tooltip__popper,
	.el-tooltip__popper.is-dark {
		background: #FFFFFF;
		max-width: 400px;
		border-radius: 4px;
		border: 1px solid #e6ebf5;
		padding: 12px;
		color: black;
		line-height: 180%;
		-webkit-box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
	}

	.el-tooltip__popper[x-placement^=top] .popper__arrow {
		bottom: -6px;
		left: 50%;
		margin-right: 3px;
		border-top-color: #FFFFFF;
		border-bottom-width: 0;
		-webkit-filter: drop-shadow(0 2px 12px rgba(0, 0, 0, 0.1));
		filter: drop-shadow(0 2px 12px rgba(0, 0, 0, 0.03));
	}

	.el-tooltip__popper[x-placement^=top] .popper__arrow:after {
		position: absolute;
		display: block;
		width: 0;
		height: 0;
		border-color: transparent;
		border-style: solid;
	}

	.el-tree-node.is-expanded>.el-tree-node__children {
		border-left: 1px dashed #ccc;
		padding-left: 20px;
	}

	.el-tree-node__content {
		padding-left: 0px !important;
	}

	/* .is-current .el-tree-node__content .el-icon-caret-right:before{
	color: #ff4d4f;
} */
	.is-current>.el-tree-node__content {
		color: #ff4d4f;
	}

	.el-tree {
		display: inline-block;
		min-width: 100%;
	}

	.el-card__body {
		padding: 20px;
	}
</style>
